package main

import (
	_ "database/sql/driver"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"log"
	"math/rand"
	"net/http"
	"time"
)

//type People struct {
//	gorm.Model
//	Name string `gorm:"type:varchar(20);not null"`
//	Telephone string `gorm:"varchar(11);not null;unique"`
//	Password string `gorm:“size:255;not null"`
//}

type Peoples struct {
	gorm.Model
	Sno string
	Sname string
	password string
}

var db *gorm.DB

func main() {
	InitDB()
	//user := peoples{sno: 2,sname: "ming"}
	//result := db.Create(&user)
	//fmt.Println(result)
	r := gin.Default()
	r.POST("/api/auth/register", func(ctx *gin.Context) {
		//获取参数
		sname:=ctx.PostForm("sname")
		sno:=ctx.PostForm("sno")
		password:=ctx.PostForm("password")
		//数据验证
		if len(sno) != 11 {
			ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"学号必须为11号"})
			return
		}
		if len(password) < 6 {
			ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"密码不能少于6位"})
			return
		}
		//如果名称没有传，
		if len(sname) == 0 {
			sname = RandomString(10)
			return
		}
		log.Println(sname,sno,password)
		//判断手机号是否存在
		if isSnoExists(db,sno) {
			ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"学生已经存在"})
			return
		}
		//创建用户
		newPeople := Peoples{
			Sno: sno,
			Sname: sname,
			password: password,
		}
		db.Create(&newPeople)
		//返回结果
		ctx.JSON(200, gin.H{
			"msg": "注册成功",
		})
	})
	panic(r.Run())// listen and serve on 0.0.0.0:8080
}

func RandomString(n int) string {
	var letters = []byte("asddasdawawrfafdadfadwadadwadadwa")
	result:=make([]byte,n)
	rand.Seed(time.Now().Unix())
	for i := range letters {
		result[i] = letters[rand.Intn(len(letters))]
	}
	return string(result)
}

func isSnoExists(db *gorm.DB,sno string) bool {
	var people Peoples
	db.Where("sno = ?",sno).First(&people)
	if people.ID != 0 {
		return true
	} else {
		return false
	}
}
func InitDB() {
	var err error
	args := fmt.Sprintf("user=%s password=%s dbname=%s host=%s port=%s sslmode=disable TimeZone=Asia/Shanghai",
		"postgres",
		"dujiahui",
		"test",
		"localhost",
		"5432",
	)
	db,err = gorm.Open(postgres.Open(args), &gorm.Config{})
	if err != nil {
		panic("faied to connect database,err:" + err.Error())
		return
	}
	db.AutoMigrate(&Peoples{})
}
